<?php

namespace app\index\service;

use app\common\model\ToolModel;
use app\index\model\ExchangeModel;
class ExchangeService
{
    //通过接口获取汇率
    public static function getExchangeByApi()
    {
        $url = 'http://www.boc.cn/sourcedb/whpj/index.html';    //中国银行汇率地址
        $content = file_get_contents($url);
        if($content){
            $begin = strpos($content,'<table cellpadding="0" align="left" cellspacing="0" width="100%">');
            $end = strpos($content,'发布-end--')-29;
            $content = trim(substr($content,$begin,($end - $begin)));
        }
        $content=str_replace(array('</table>','<table cellpadding="0" align="left" cellspacing="0" width="100%">',' </tr>'),'',$content);
        $temp=explode('<tr>',$content);
        unset($temp[0]);
        unset($temp[1]);
        $tempData=[];
        if(!empty($temp)){
            foreach ($temp as $v){
                $h=explode("</td>",$v);
                foreach ($h as &$v2){
                    $v2=str_replace("<td>","",trim($v2));
                }
                unset($h[8]);
                $arr=[];
                $arr['name']=$h[0];
                $arr['fBuyPri']=$h[1];
                $arr['mBuyPri']=$h[2];
                $arr['fSellPri']=$h[3];
                $arr['mSellPri']=$h[4];
                $arr['bankConversionPri']=$h[5];
                $arr['date']=$h[6].' '.$h[7];
                $arr['ctime']=TIME;
                $arr['utime']=TIME;
                $tempData[]=$arr;
            }
         }
        ToolModel::dbInsertOrUpdate('exchange_rate',$tempData);
    }
    public static function getList($param){
        if(empty($param['down'])){
            $titles=[];
        }else{
            $titles=[
                'name'=>'货币名称',
                'fBuyPri'=>'现汇买入价',
                'mBuyPri'=>'现钞买入价',
                'fSellPri'=>'现汇卖出价',
                'mSellPri'=>'现钞卖出价',
                'bankConversionPri'=>'中行折算价',
                'date'=>'发布日期'
            ];
        }
        return ExchangeModel::getList($param,$titles,null);
    }

}
